<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 用户列表 -->
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <SmForm
            ref="queryFormRef"
            :inline="true"
            label-width="150px"
            v-model="queryParams"
            :options="searchFormOptions"
            :getModelValue="getSearchFormData"
          >
            <template #action>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
            </template>
          </SmForm>
        </div>

        <el-card shadow="hover" class="data-table">
          <div class="data-table__toolbar">
            <div class="data-table__toolbar--actions">
              <el-button
                v-hasPerm="['sys:user:add']"
                type="success"
                icon="plus"
                @click="openForm('create')"
              >
                新增
              </el-button>
              <!-- <el-button
                v-hasPerm="'sys:user:delete'"
                type="danger"
                icon="delete"
                :disabled="selectIds.length === 0"
                @click="handleDelete()"
              >
                删除
              </el-button> -->
            </div>
            <div class="data-table__toolbar--tools">
              <!-- <el-button
                v-hasPerm="'sys:user:import'"
                icon="upload"
                @click="handleOpenImportDialog"
              >
                导入
              </el-button>

              <el-button
                v-hasPerm="'sys:user:export'"
                icon="download"
                @click="handleExport(queryParams)"
              >
                导出
              </el-button> -->
            </div>
          </div>

          <SmTable
            isSelection
            border
            :loading="loading"
            :options="tableOptions"
            :data="list"
            :total="total"
            v-model:currentPage="queryParams.pageNum"
            v-model:pageSize="queryParams.pageSize"
            @pagination="getList"
            @selection-change="handleSelectionChange"
          >
            <template #roles="{ scope }">
              <div v-for="item in scope?.row?.roles">
                {{ item.name }}
              </div>
            </template>

            <template #operate="{ scope }">
              <el-button
                v-hasPerm="'sys:user:edit'"
                type="primary"
                icon="edit"
                link
                size="small"
                @click="openForm('update', scope.row.id)"
              >
                查看
              </el-button>
            </template>
          </SmTable>
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户导入 -->
    <!-- <UserImport v-model="importDialogVisible" @import-success="handleQuery()" /> -->

    <OpenForm ref="formRef" @success="getList" />
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app-store";
import { DeviceEnum } from "@/enums/settings/device.enum";

import UserAPI, { UserForm, UserPageQuery, UserPageVO } from "@/api/system/user-api";
import DeptAPI from "@/api/system/dept-api";
import RoleAPI from "@/api/system/role-api";

// import DeptTree from "./components/DeptTree.vue";
// import UserImport from "./components/UserImport.vue";

import OpenForm from "./components/OpenForm.vue";
import { useTable } from "./hooks/useTable";
import { useSearchForm } from "./hooks/search";
import { useBatch } from "./hooks/useBatch";
import { deleteByIdsUser } from "@/api/user";

defineOptions({
  name: "EffectiveCirculationCoordinateForm",
  inheritAttrs: false,
});

const appStore = useAppStore();

// const queryFormRef = ref();
const userFormRef = ref();

// const queryParams = reactive<UserPageQuery>({
//   pageNum: 1,
//   pageSize: 10,
// });

const pageData = ref<UserPageVO[]>();
// const total = ref(0);
// const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: "新增用户",
});

const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));

const formData = reactive<UserForm>({
  status: 1,
});

// 选中的用户ID
const selectIds = ref<number[]>([]);
// 部门下拉数据源
const deptOptions = ref<OptionType[]>();
// 角色下拉数据源
const roleOptions = ref<OptionType[]>();
// 导入弹窗显示状态
const importDialogVisible = ref(false);

// 获取数据
// async function fetchData() {
//   loading.value = true;
//   try {
//     const data = await UserAPI.getPage(queryParams);
//     pageData.value = data.list;
//     total.value = data.total;
//   } finally {
//     loading.value = false;
//   }
// }

// 查询（重置页码后获取数据）
// function handleQuery() {
//   queryParams.pageNum = 1;
//   fetchData();
// }

// 重置查询
// function handleResetQuery() {
//   queryFormRef.value.resetFields();
//   queryParams.pageNum = 1;
//   queryParams.deptId = undefined;
//   queryParams.createTime = undefined;
//   fetchData();
// }

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

// 重置密码
function hancleResetPassword(row: UserPageVO) {
  ElMessageBox.prompt("请输入用户【" + row.username + "】的新密码", "重置密码", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(
    ({ value }) => {
      if (!value || value.length < 6) {
        ElMessage.warning("密码至少需要6位字符，请重新输入");
        return false;
      }
      UserAPI.resetPassword(row.id, value).then(() => {
        ElMessage.success("密码重置成功，新密码是：" + value);
      });
    },
    () => {
      ElMessage.info("已取消重置密码");
    }
  );
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(id?: string) {
  dialog.visible = true;
  // 加载角色下拉数据源
  roleOptions.value = await RoleAPI.getOptions();
  // 加载部门下拉数据源
  deptOptions.value = await DeptAPI.getOptions();

  if (id) {
    dialog.title = "修改用户";
    UserAPI.getFormData(id).then((data) => {
      Object.assign(formData, { ...data });
    });
  } else {
    dialog.title = "新增用户";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        UserAPI.update(userId, formData)
          .then(() => {
            ElMessage.success("修改用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        UserAPI.create(formData)
          .then(() => {
            ElMessage.success("新增用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**
 * 删除用户
 *
 * @param id  用户ID
 */
function handleDelete(id?: number) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      deleteByIdsUser(userIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开导入弹窗
function handleOpenImportDialog() {
  importDialogVisible.value = true;
}

// 导出用户
// function handleExport() {
//   UserAPI.export(queryParams).then((response: any) => {
//     const fileData = response.data;
//     const fileName = decodeURI(response.headers["content-disposition"].split(";")[1].split("=")[1]);
//     const fileType =
//       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

//     const blob = new Blob([fileData], { type: fileType });
//     const downloadUrl = window.URL.createObjectURL(blob);

//     const downloadLink = document.createElement("a");
//     downloadLink.href = downloadUrl;
//     downloadLink.download = fileName;

//     document.body.appendChild(downloadLink);
//     downloadLink.click();

//     document.body.removeChild(downloadLink);
//     window.URL.revokeObjectURL(downloadUrl);
//   });
// }

const {
  tableOptions,
  list,
  total,
  loading,
  queryParams,
  getList,
  handleQuery,
  handleResetQuery,
  queryFormRef,
  formRef,
  openForm,
} = useTable();

const { getSearchFormData, searchFormOptions } = useSearchForm(handleQuery, queryParams);
const { handleExport } = useBatch();

onMounted(() => {
  getList();
  // handleQuery();
});
</script>
